<template>
  <div class="profile-container">
    <!-- 用户信息展示区域 -->
    <el-card
        shadow="hover"
        class="profile-card"
        enter-active-class="animate__animated animate__fadeIn"
    >
      <div class="profile-header">
        <div class="avatar-container">
          <el-avatar
              :src="getUserAvatar()"
              :size="160"
              class="user-avatar"
              @error="handleAvatarLoadError"
          ></el-avatar>
          <div class="avatar-upload">
            <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :on-success="handleAvatarSuccess"
                :on-error="handleAvatarError"
                action="#"
                :http-request="customUpload"
            >
              <el-button size="small" type="primary" class="upload-btn">
                <i class="el-icon-camera"></i>
                更换头像
              </el-button>
            </el-upload>
          </div>
        </div>
        <h2 class="username">{{ form.username }}</h2>
      </div>

      <div class="profile-info">
        <div class="info-item">
          <i class="el-icon-message info-icon"></i>
          <span class="info-label">邮箱：</span>
          <span class="info-value">{{ form.email }}</span>
        </div>
        <div class="info-item">
          <i class="el-icon-time info-icon"></i>
          <span class="info-label">创建时间：</span>
          <span class="info-value">{{ form.createdAt }}</span>
        </div>
      </div>

      <div class="action-buttons">
        <el-button
            @click="showDialog('nickname')"
            class="action-btn"
            icon="el-icon-edit"
        >
          修改昵称
        </el-button>
        <el-button
            @click="showDialog('password')"
            class="action-btn"
            icon="el-icon-lock"
        >
          修改密码
        </el-button>
        <el-button
            @click="showDialog('email')"
            class="action-btn"
            icon="el-icon-envelope"
        >
          修改邮箱
        </el-button>
        <el-button
            @click="goBack"
            class="action-btn"
            icon="el-icon-back"
            type="info"
        >
          返回主页
        </el-button>
      </div>
    </el-card>

    <!-- 修改昵称对话框 -->
    <el-dialog
        v-model="dialog.visible"
        title="修改昵称"
        width="400px"
        :before-close="resetDialog"
        v-if="dialog.type === 'nickname'"
    >
      <el-form :model="dialogForm" ref="nicknameForm" label-width="80px">
        <el-form-item
            label="昵称"
            prop="nickname"
            :rules="rules.nickname"
        >
          <el-input v-model="dialogForm.nickname" placeholder="请输入新昵称"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetDialog">取消</el-button>
          <el-button type="primary" @click="saveNickname">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改邮箱对话框 -->
    <el-dialog
        v-model="dialog.visible"
        title="修改邮箱"
        width="400px"
        :before-close="resetDialog"
        v-if="dialog.type === 'email'"
    >
      <el-form :model="dialogForm" ref="emailForm" label-width="80px">
        <el-form-item
            label="邮箱"
            prop="email"
            :rules="rules.email"
        >
          <el-input v-model="dialogForm.email" placeholder="请输入新邮箱"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetDialog">取消</el-button>
          <el-button type="primary" @click="saveEmail">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog
        v-model="dialog.visible"
        title="修改密码"
        width="400px"
        :before-close="resetDialog"
        v-if="dialog.type === 'password'"
    >
      <el-form :model="dialogForm" ref="passwordForm" label-width="80px">
        <el-form-item
            label="新密码"
            prop="newPassword"
            :rules="rules.newPassword"
        >
          <el-input 
            v-model="dialogForm.newPassword" 
            type="password" 
            placeholder="请输入新密码"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item
            label="确认密码"
            prop="confirmPassword"
            :rules="rules.confirmPassword"
        >
          <el-input 
            v-model="dialogForm.confirmPassword" 
            type="password" 
            placeholder="请再次输入新密码"
            show-password
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetDialog">取消</el-button>
          <el-button type="primary" @click="savePassword">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { useAuthStore } from '@/store/authStore';
import userApi from '@/api/user/userApi.js';
import fileApi from '@/api/file/fileApi.js'; // Added for avatar upload
import { getUserAvatarUrl, handleAvatarError } from '@/utils/avatarUtils';

export default {
  name: 'UserProfile',
  data() {
    return {
      form: {
        username: '',
        email: '',
        password: '******',
        avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
        createdAt: ''
      },
      dialog: {
        visible: false,
        type: '' //'nickname' | 'password' | 'email'
      },
      dialogForm: {
        nickname: '',
        email: '',
        newPassword: '',
        confirmPassword: ''
      },
      rules: {
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入有效的邮箱地址', trigger: ['blur', 'change'] }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { validator: this.validateConfirmPassword, trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.loadUserInfo();
  },
  methods: {
    validateConfirmPassword(rule, value, callback) {
      if (value !== this.dialogForm.newPassword) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    },
    loadUserInfo() {
      const authStore = useAuthStore();
      if (authStore.user) {
        // 从 store 中获取用户信息
        this.form = {
          ...authStore.user,
          password: '******', // 不显示真实密码
          avatar: authStore.user.avatar || 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
        };
      } else {
        // 如果没有用户信息，跳转到登录页
        this.$router.push('/login');
      }
    },
    showDialog(type) {
      console.log("点击成功");
      this.dialog.type = type;
      this.dialog.visible = true;

      this.$nextTick(() => {
        if (this.$refs[`${type}Form`]) {
          this.$refs[`${type}Form`].clearValidate();
        }
      });

      if (type === 'nickname') {
        this.dialogForm.nickname = this.form.username;
      } else if (type === 'email') {
        this.dialogForm.email = this.form.email;
      } else if (type === 'password') {
        this.dialogForm.newPassword = '';
        this.dialogForm.confirmPassword = '';
      }
    },
    resetDialog() {
      this.dialog.visible = false;
      this.dialog.type = '';
      this.dialogForm.nickname = '';
      this.dialogForm.email = '';
      this.dialogForm.newPassword = '';
      this.dialogForm.confirmPassword = '';
    },
    saveNickname() {
      this.$refs.nicknameForm.validate(valid => {
        if (valid) {
          const authStore = useAuthStore();
          const updateData = {
            ...this.form,
            username: this.dialogForm.nickname
          };
          
          userApi.updateUser(authStore.user.id, updateData)
            .then(response => {
              this.form.username = this.dialogForm.nickname;
              // 更新 store 中的用户信息
              authStore.login(response.data);
              this.$message.success('昵称修改成功');
              this.resetDialog();
            })
            .catch(error => {
              this.$message.error('修改失败，请稍后重试');
            });
        }
      });
    },
    saveEmail() {
      this.$refs.emailForm.validate(valid => {
        if (valid) {
          const authStore = useAuthStore();
          const updateData = {
            ...this.form,
            email: this.dialogForm.email
          };
          
          userApi.updateUser(authStore.user.id, updateData)
            .then(response => {
              this.form.email = this.dialogForm.email;
              // 更新 store 中的用户信息
              authStore.login(response.data);
              this.$message.success('邮箱修改成功');
              this.resetDialog();
            })
            .catch(error => {
              this.$message.error('修改失败，请稍后重试');
            });
        }
      });
    },
    savePassword() {
      this.$refs.passwordForm.validate(valid => {
        if (valid) {
          const authStore = useAuthStore();
          const updateData = {
            ...this.form,
            password: this.dialogForm.newPassword
          };
          
          userApi.updateUser(authStore.user.id, updateData)
            .then(response => {
              this.form.password = '******';
              // 更新 store 中的用户信息
              authStore.login(response.data);
              this.$message.success('密码修改成功');
              this.resetDialog();
            })
            .catch(error => {
              this.$message.error('修改失败，请稍后重试');
            });
        }
      });
    },
    goBack() {
      this.$router.push('/home');
    },
    
    // 头像上传相关方法
    beforeAvatarUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isImage) {
        this.$message.error('只能上传图片文件!');
        return false;
      }
      if (!isLt5M) {
        this.$message.error('图片大小不能超过 5MB!');
        return false;
      }
      return true;
    },
    
    customUpload(options) {
      const { file } = options;
      
      fileApi.uploadAvatar(file)
        .then(response => {
          const avatarUrl = response.data;
          this.handleAvatarSuccess(response, file);
        })
        .catch(error => {
          this.handleAvatarError(error);
        });
    },
    
    handleAvatarSuccess(response, file) {
      const avatarUrl = response.data;
      console.log('头像上传成功，URL:', avatarUrl);
      
      // 更新本地显示
      this.form.avatar = avatarUrl;
      
      // 更新后端数据库
      const authStore = useAuthStore();
      console.log('更新头像，用户ID:', authStore.user.id, '头像URL:', avatarUrl);
      
      userApi.updateAvatar(authStore.user.id, avatarUrl)
        .then(updateResponse => {
          console.log('头像更新成功:', updateResponse.data);
          // 更新 store 中的用户信息
          authStore.login(updateResponse.data);
          this.$message.success('头像上传成功');
        })
        .catch(error => {
          console.error('头像更新失败:', error);
          this.$message.error('头像更新失败: ' + (error.response?.data || error.message));
        });
    },
    
    handleAvatarError(error) {
      console.error('头像上传失败:', error);
      this.$message.error('头像上传失败，请重试');
    },

    handleAvatarLoadError() {
      console.warn('头像加载失败，使用默认头像');
      this.form.avatar = getUserAvatarUrl();
    },

    getUserAvatar() {
      return getUserAvatarUrl(this.form.avatar);
    }
  }
};
</script>

<style scoped>
.profile-container {
  min-height: 100vh;
  background-color: #f0f2f5;
  padding: 40px 20px;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.profile-card {
  width: 90%;
  max-width: 500px;
  border-radius: 16px;
  overflow: hidden;
  transition: all 0.3s ease;
  background-color: #ffffff;
  padding: 30px 20px;
}

.profile-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 20px rgba(0, 0, 0, 0.1);
}

.profile-header {
  text-align: center;
  margin-bottom: 30px;
}

.avatar-container {
  position: relative;
  display: inline-block;
}

.avatar-upload {
  position: absolute;
  bottom: 0;
  right: 0;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  padding: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.upload-btn {
  border-radius: 50%;
  width: 40px;
  height: 40px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-uploader {
  display: inline-block;
}

.user-avatar {
  border: 4px solid #409eff;
  transition: all 0.3s ease;
}

.user-avatar:hover {
  transform: scale(1.05);
  box-shadow: 0 6px 15px rgba(64, 158, 255, 0.3);
}

.username {
  margin-top: 20px;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  letter-spacing: 0.5px;
}

.profile-info {
  margin-bottom: 30px;
  border-top: 1px solid #f0f0f0;
  padding-top: 20px;
}

.info-item {
  display: flex;
  align-items: center;
  padding: 12px 15px;
  border-radius: 8px;
  margin-bottom: 10px;
  transition: background-color 0.2s;
}

.info-item:hover {
  background-color: #f5f7fa;
}

.info-icon {
  color: #409eff;
  margin-right: 12px;
  font-size: 18px;
}

.info-label {
  color: #606266;
  width: 80px;
  font-weight: 500;
}

.info-value {
  color: #303133;
  flex: 1;
  word-break: break-all;
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 12px;
  margin-top: 10px;
}

.action-btn {
  transition: all 0.25s ease;
  border-radius: 6px;
  padding: 8px 18px;
  font-size: 14px;
}

.action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.25);
}

.dialog-footer {
  text-align: right;
  padding-top: 20px;
}

/* 动画效果 */
.animate__fadeIn {
  animation: fadeIn 0.5s ease forwards;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式调整 */
@media (max-width: 480px) {
  .profile-card {
    padding: 20px 15px;
  }

  .action-buttons {
    flex-direction: column;
  }

  .action-btn {
    width: 100%;
    margin: 5px 0;
  }

  .username {
    font-size: 20px;
  }
}
</style>
